package com.dlyk.config.handler;

import com.dlyk.constant.Constants;
import com.dlyk.manager.RedisStringManager;
import com.dlyk.mapper.UserMapper;
import com.dlyk.model.User;
import com.dlyk.result.R;
import com.dlyk.service.UserService;
import com.dlyk.util.JSONUtils;
import com.dlyk.util.JWTUtils;
import com.dlyk.util.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 登录成功处理器
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private RedisStringManager redisStringManager;

    // 这里为了方便就直接注入Mapper了
    @Resource
    private UserMapper userMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        // 获取登录用户
        User user = (User) authentication.getPrincipal();

        // 设置最后登录时间
        user.setLastLoginTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);

        // 将User对象转成json
        String userJson = JSONUtils.toJSON(user);

        // 生成jwt
        String jwt = JWTUtils.createJWT(userJson);

        // 将jwt写入redis
        redisStringManager.setValue(Constants.REDIS_JWT_KEY + user.getId(), jwt);

        // 设置jwt的过期时间（如果用户勾选了记住我，过期时间是7天，否则是30分钟）
        // 获取前端提交的参数
        String rememberMe = request.getParameter("rememberMe");
        // 判断是否勾选
        if (Boolean.parseBoolean(rememberMe)) {
            redisStringManager.expire(Constants.REDIS_JWT_KEY + user.getId(), Constants.EXPIRE_TIME, TimeUnit.SECONDS);
        } else {
            redisStringManager.expire(Constants.REDIS_JWT_KEY + user.getId(), Constants.DEFAULT_EXPIRE_TIME, TimeUnit.SECONDS);
        }

        // 将jwt使用R对象进行封装
        R result = R.OK(jwt);

        // 将R对象转成json
        String resultJson = JSONUtils.toJSON(result);

        // 将R对象以json形式返回给前端
        ResponseUtils.write(response, resultJson);
    }

}

